#include "article_service.h"

namespace jztzp {

void ArticleMainHandler::GetContent(ArticleResult& _return, const int32_t id) {
  string content;
  if (redis_adapter_.GetContent(id, &content) >= 0) {
    _return.__set_success(true);
    _return.__set_content(content);
    return;
  }

  mysqlpp::ScopedConnection cp(db_pool_, true);
  if (!cp) {
    LOG_ERROR("Failed to get a connection from the pool!");
    return;
  }

  mysqlpp::Query query(cp->query());
  query << "SELECT content FROM article_content WHERE id=" << id;
  mysqlpp::StoreQueryResult res;
  try {
    res = query.store();
    if (res) {
      if (res.num_rows() > 0) {
        _return.__set_success(true);
        content.assign(res[0][0].c_str(), res[0][0].size());
        _return.__set_content(content);
        LOG_INFO("GetContent(" << id << ") size=" << content.size());

        redis_adapter_.SetContent(id, content);
      } else {
        _return.__set_success(false);
        _return.__set_reason("article not found");
        LOG_INFO("GetContent(" << id << ") not exist.");
      }
    } else {
      _return.__set_success(false);
      _return.__set_reason("db null res");
      LOG_INFO("GetContent(" << id << ") null res.");
    }
  } catch (mysqlpp::Exception & e) {
    _return.__set_success(false);
    _return.__set_reason(e.what());
    LOG_INFO("GetContent(" << id << ") err:" << e.what());
  }
}

int32_t ArticleMainHandler::UpdateContent(int32_t article_id, const std::string& content) {
  // redis_adapter_.SetContent(article_id, content);
  redis_adapter_.RemoveContent(article_id);

  mysqlpp::ScopedConnection cp(db_pool_, true);
  if (!cp) {
    LOG_ERROR("Failed to get a connection from the pool!");
    return -1;
  }

  mysqlpp::Query query(cp->query());
  query << "UPDATE article_content SET content = " << mysqlpp::quote << content << " WHERE " << "id=" << article_id;

  bool res = false;
  try {
    res = query.exec();
  } catch (mysqlpp::Exception & e) {
    LOG_ERROR(query.str() << " error:" << e.what());
    return -1;
  }

  LOG_INFO("update content ok, id=" << article_id);
  return 0;
}

}


int main(int argc, char **argv) {
  LOG_INIT("./article.log", "DEBUG");
  int port = 9093;

  LOG_INFO("listens on port " << port);
  using namespace jztzp;
  ThriftService<ArticleMainHandler, ArticleMainProcessor> service;
  service.Start(port);
  return 0;
}

/*
extern "C" {

void ServiceEntry() {
  LOG_INIT("./article.log", "DEBUG");
  int port = 9093;
  LOG_INFO("listens on port " << port);

  using namespace jztzp;
  ThriftService<ArticleMainHandler, ArticleMainProcessor> service;
  service.Start(port);
}

}
*/
